"""
音频流管理服务模块
提供流媒体会话管理、缓冲策略和并发控制功能
"""

from typing import Dict, List, Set, Optional, Tuple, Any, Union

from .session_manager import (
    SessionManager,
    SessionState,
    StreamSession,
    session_manager
)
from .buffer_manager import (
    SmartBuffer,
    BufferState,
    BufferConfig,
    BufferStats,
    AudioChunk,
    PreloadStrategy,
    buffer_manager
)
from .concurrent_manager import (
    ConcurrencyManager,
    ConcurrencyLevel,
    StreamResource,
    ResourceLimits,
    ResourceUsage,
    Priority,
    concurrency_manager
)
from .adaptive_quality import (
    AdaptiveQualityManager,
    QualitySession,
    QualityLevel,
    QualityConfig,
    NetworkMetrics,
    PerformanceMetrics,
    AdaptationStrategy,
    NetworkCondition,
    adaptive_quality_manager
)

__all__ = [
    # 会话管理
    'SessionManager',
    'SessionState',
    'StreamSession',
    'session_manager',
    
    # 缓冲管理
    'SmartBuffer',
    'BufferState',
    'BufferConfig',
    'BufferStats',
    'AudioChunk',
    'PreloadStrategy',
    'buffer_manager',
    
    # 并发管理
    'ConcurrencyManager',
    'ConcurrencyLevel',
    'StreamResource',
    'ResourceLimits',
    'ResourceUsage',
    'Priority',
    'concurrency_manager',
    
    # 自适应质量
    'AdaptiveQualityManager',
    'QualitySession',
    'QualityLevel',
    'QualityConfig',
    'NetworkMetrics',
    'PerformanceMetrics',
    'AdaptationStrategy',
    'NetworkCondition',
    'adaptive_quality_manager'
]

# 版本信息
__version__ = '1.0.0'
__author__ = 'Offline Language Player Team'


# 服务初始化
async def init_streaming_services():
    """初始化流媒体服务"""
    try:
        # 启动并发管理器
        await concurrency_manager.start()
        
        logger = get_logger(__name__)
        logger.info("Streaming services initialized successfully")
        return True
        
    except Exception as e:
        logger = get_logger(__name__)
        logger.error(f"Failed to initialize streaming services: {e}")
        return False


# 服务清理
async def cleanup_streaming_services():
    """清理流媒体服务"""
    try:
        # 停止并发管理器
        await concurrency_manager.stop()
        
        # 停止自适应质量管理器
        await adaptive_quality_manager.stop()
        
        # 停止会话管理器
        session_manager.stop_cleanup_task()
        
        logger = get_logger(__name__)
        logger.info("Streaming services cleaned up successfully")
        return True
        
    except Exception as e:
        logger = get_logger(__name__)
        logger.error(f"Failed to cleanup streaming services: {e}")
        return False


# 便捷函数
async def create_stream_session(
    user_id: str,
    session_type: str = "single",
    **kwargs
) -> StreamSession:
    """创建流会话（便捷函数）"""
    return await session_manager.create_session(
        user_id=user_id,
        session_type=session_type,
        **kwargs
    )


async def create_stream_buffer(
    buffer_id: str,
    config: Optional[BufferConfig] = None
) -> SmartBuffer:
    """创建流缓冲区（便捷函数）"""
    return await buffer_manager.create_buffer(buffer_id, config)


async def request_stream_resources(
    stream_id: str,
    user_id: str,
    session_id: str,
    concurrency_level: ConcurrencyLevel = ConcurrencyLevel.MEDIUM,
    **kwargs
) -> tuple[bool, str]:
    """请求流资源（便捷函数）"""
    return await concurrency_manager.request_stream(
        stream_id=stream_id,
        user_id=user_id,
        session_id=session_id,
        concurrency_level=concurrency_level,
        **kwargs
    )


async def create_quality_session(
    session_id: str,
    user_id: str,
    initial_quality: QualityLevel = QualityLevel.MEDIUM,
    strategy: AdaptationStrategy = AdaptationStrategy.BALANCED,
    **kwargs
) -> QualitySession:
    """创建质量会话（便捷函数）"""
    return await adaptive_quality_manager.create_session(
        session_id=session_id,
        user_id=user_id,
        initial_quality=initial_quality,
        strategy=strategy,
        **kwargs
    )


# 导入必要的模块
from ...core.logging import get_logger
from typing import Optional, Tuple
